package com.powernode.springmvc.controller;

import com.powernode.springmvc.bean.User;
import com.powernode.springmvc.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

@Controller
public class UserController {
    @Autowired
    private UserDao userDao;

    @RequestMapping(path = "/user", method = RequestMethod.GET)
    public String list(Model model) {
        //查询数据库，获取用户列表
        List<User> userList = userDao.findAll();
        model.addAttribute("userList", userList);
        return "user_list";
    }

    @RequestMapping(path = "/user", method = RequestMethod.POST)
    public String addUser(User user) {
        //新增用户
        userDao.addUser(user);
        return "redirect:/user";
    }

    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
    public String detailUser(@PathVariable Long id, Model model) {
        User user = userDao.getUserById(id);
        model.addAttribute("user", user);
        return "user_edit";
    }

    @RequestMapping(path = "/user", method = RequestMethod.PUT)
    public String editUser(User user) {
        userDao.editUser(user);
        return "redirect:/user";
    }

    @RequestMapping(path = "/user/{id}", method = RequestMethod.DELETE)
    public String deleteUser(@PathVariable Long id) {
        userDao.deleteUser(id);
        return "redirect:/user";
    }
}
